img1 = imread('./img1.png');

figure;
subplot(1, 2, 1); imshow(img1); title("img1", FontWeight="bold");
subplot(1, 2, 2); imhist(img1); title("hist1", FontWeight="bold");
% 理论上来说以直方图双峰之间谷底灰度值作为阈值，可以将图像和背景分开
% subplot(3, 2, 3); im2bw(img1, 0.4);
% subplot(3, 2, 4); im2bw(img1, 0.45);

% 求解阈值
figure;
thresh = graythresh(img1);
bw = imbinarize(img1, "global");
subplot(1, 2, 1); imshowpair(img1, bw, 'montage');
title("img1 binarized", FontWeight="bold");
subplot(1, 2, 2); imshowpair(img1, im2bw(img1, thresh), 'montage'); 
title("img1 threshold", FontWeight="bold");

% img2
figure;
img2 = imread('./img2.png');
subplot(1, 2, 1); imshow(img2); title("img2", FontWeight="bold");
subplot(1, 2, 2); imhist(img2); title("hist2", FontWeight="bold");

figure;
thresh2 = graythresh(img2);
bw2 = imbinarize(img2, 'global');
subplot(1, 2, 1); imshowpair(img2, bw2, 'montage');
title("img2 binarized", FontWeight="bold");
subplot(1, 2, 2); imshowpair(img2, im2bw(img2, thresh), 'montage');
title("img2 threshold", FontWeight="bold");
% img3
figure;
img3 = imread('./img3.png');
subplot(1, 2, 1); imshow(img3); title("img3", FontWeight="bold");
subplot(1, 2, 2); imhist(img3); title("hist3", FontWeight="bold");

figure;
thresh3 = graythresh(img3);
bw3 = imbinarize(img3, 'global');
subplot(1, 2, 1); imshowpair(img3, bw3, 'montage');
title("img3 binarized", FontWeight="bold");
subplot(1, 2, 2); imshowpair(img3, im2bw(img3, thresh3), 'montage');
title("img3 threshold", FontWeight="bold");

